<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :init-fullscreen="true">
    <el-row>
      <el-col :span="12">
       
          <!-- <el-button type="primary" @click="openCheck('create')">验收</el-button> -->
          <el-button :disabled="formType != 'process'" type="primary" @click="openIn()">入库</el-button>
          <el-button :disabled="formType != 'process'" type="primary" @click="finishPlan()">完工</el-button>
     
      </el-col>

      <el-col :span="12">
        <div style="display: flex; justify-content: flex-end; gap: 8px">
          <el-button @click="getList">
            <Icon icon="ep:refresh-right" class="mr-5px" />
            刷新
          </el-button>
          <el-dropdown split-button>
            查看日志
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="openPlanLog('领料')">领料日志</el-dropdown-item>
                <el-dropdown-item @click="openPlanLog('退料')">退料日志</el-dropdown-item>
                <el-dropdown-item @click="openPlanLog('用料')">用料日志</el-dropdown-item>
                <el-dropdown-item @click="openPlanLog('入库')">入库日志</el-dropdown-item>
                <!--                <el-dropdown-item>请购日志</el-dropdown-item>-->
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-col>
    </el-row>
    <!--    <el-descriptions style="margin-top: 20px" title="" :column="4" border>-->
    <!--      <el-descriptions-item label="生产单号：">{{ formData.no }}</el-descriptions-item>-->
    <!--      <el-descriptions-item label="产品编码:">{{ formData.productBarCode }}</el-descriptions-item>-->
    <!--      <el-descriptions-item label="产品名称:">{{ formData.productName }}</el-descriptions-item>-->
    <!--      <el-descriptions-item label="合计成本:">{{ formData.primePrice }}</el-descriptions-item>-->
    <!--      <el-descriptions-item label="订购数量:">{{-->
    <!--          formData.orderCount + formData.productUnitName-->
    <!--        }}-->
    <!--      </el-descriptions-item>-->
    <!--      <el-descriptions-item label="生产数量:">{{-->
    <!--          formData.produceCount + formData.productUnitName-->
    <!--        }}-->
    <!--      </el-descriptions-item>-->
    <!--      <el-descriptions-item label="销售订单号:">{{ formData.salesOrderNo }}</el-descriptions-item>-->
    <!--      <el-descriptions-item label="计划完工:">{{-->
    <!--          formatDate(formData.finishPlanTime, 'YYYY-MM-DD')-->
    <!--        }}-->
    <!--      </el-descriptions-item>-->
    <!--      <el-descriptions-item label="验收合格:">{{-->
    <!--          formData.checkCount + formData.productUnitName-->
    <!--        }}-->
    <!--      </el-descriptions-item>-->
    <!--      <el-descriptions-item label="已入库数:">{{ formData.inCount + formData.productUnitName }}</el-descriptions-item>-->

    <!--      <el-descriptions-item label="实际完工:">{{-->
    <!--          formatDate(formData.realFinishTime, 'YYYY-MM-DD')-->
    <!--        }}-->
    <!--      </el-descriptions-item>-->
    <!--      <el-descriptions-item label="单据备注:">{{ formData.remark }}</el-descriptions-item>-->
    <!--    </el-descriptions>-->
    <el-row style="margin-top: 20px; border: 1px solid #e5e7eb; border-radius: 4px; padding: 5px 0">
      <!-- 第一行 -->
      <el-col :span="6" class="p-3 border-r border-b">
        <div
          ><span class="text-sm text-gray-500">生产单号：</span
          ><span class="ml-2">{{ formData.no }}</span></div
        >
      </el-col>
      <el-col :span="6" class="p-3 border-r border-b">
        <div
          ><span class="text-sm text-gray-500">产品编码：</span
          ><span class="ml-2">{{ formData.productBarCode }}</span>
        </div>
      </el-col>
      <el-col :span="6" class="p-3 border-r border-b">
        <div
          ><span class="text-sm text-gray-500">产品名称：</span
          ><span class="ml-2">{{ formData.productName }}</span>
        </div>
      </el-col>
      <el-col :span="6" class="p-3 border-b">
        <div
          ><span class="text-sm text-gray-500">合计成本：</span
          ><span class="ml-2">{{ formData.primePrice }}</span>
        </div>
      </el-col>

      <!-- 第二行 -->
      <el-col :span="6" class="p-3 border-r border-b">
        <div
          ><span class="text-sm text-gray-500">订购数量：</span
          ><span class="ml-2">{{ formData.orderCount + formData.productUnitName }}</span></div
        >
      </el-col>
      <el-col :span="6" class="p-3 border-r border-b">
        <div
          ><span class="text-sm text-gray-500">生产数量：</span
          ><span class="ml-2">{{ formData.produceCount + formData.productUnitName }}</span></div
        >
      </el-col>
      <el-col :span="6" class="p-3 border-r border-b">
        <div
          ><span class="text-sm text-gray-500">销售订单号：</span
          ><span class="ml-2">{{ formData.salesOrderNo }}</span>
        </div>
      </el-col>
      <el-col :span="6" class="p-3 border-b">
        <div
          ><span class="text-sm text-gray-500">计划完工：</span
          ><span class="ml-2">{{ formatDate(formData.planFinishTime, 'YYYY-MM-DD') }}</span></div
        >
      </el-col>

      <!-- 第三行 -->
      <!-- <el-col :span="6" class="p-3 border-r">
        <div
          ><span class="text-sm text-gray-500">验收合格：</span
          ><span class="ml-2">{{ formData.checkCount + formData.productUnitName }}</span></div
        >
      </el-col> -->
      <el-col :span="6" class="p-3 border-r">
        <div
          ><span class="text-sm text-gray-500">已入库数：</span
          ><span class="ml-2">{{ formData.inCount + formData.productUnitName }}</span></div
        >
      </el-col>
      <el-col :span="6" class="p-3 border-r">
        <div
          ><span class="text-sm text-gray-500">实际完工：</span
          ><span class="ml-2">{{ formatDate(formData.realFinishTime, 'YYYY-MM-DD') }}</span></div
        >
      </el-col>
      <el-col :span="6" class="p-3">
        <div
          ><span class="text-sm text-gray-500">单据备注：</span
          ><span class="ml-2">{{ formData.remark }}</span></div
        >
      </el-col>
    </el-row>

    <el-divider />
    <ContentWrap>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="1.所需物料" name="material">
          <el-table :data="formData.materialItems" class="-mt-10px">
            <el-table-column label="编码" align="center" prop="productBarCode" width="120" />
            <el-table-column label="名称" align="center" prop="productName" width="180" />
            <el-table-column label="产品属性" align="center" prop="property" width="90">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.ERP_PRODUCT_PROPERTY" :value="scope.row.property" />
              </template>
            </el-table-column>
            <el-table-column label="来源" align="center" prop="source" width="120" />
            <el-table-column label="周期（天）" align="center" prop="cycle" />
            <el-table-column label="安全库存" align="center" prop="safeStock" />
            <el-table-column label="库存" align="center" prop="stockCount" width="160">
              <template #default="scope">
                {{ scope.row.stockCount }}
                <!-- 当所需用料小于库存数量时显示相应按钮 -->
                <template v-if="scope.row.count > scope.row.stockCount">
                  <el-tag type="danger">库存缺货</el-tag>
                </template>
                <!-- 当所需用料不小于库存数量时可以显示提示或不显示任何内容 -->
                <template v-else>
                  <el-tag>库存充足</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="补货操作" align="center" prop="warehouseName" width="120">
              <template #default="scope">
                <!-- 当所需用料小于库存数量时显示相应按钮 -->
                <el-button
                  v-if="scope.row.source === '采购' || scope.row.source === '生产或采购'"
                  link
                  type="primary"
                  @click="handlePurchase(scope.row)"
                >
                  采购
                </el-button>
                <el-button
                  v-if="scope.row.source === '生产' || scope.row.source === '生产或采购'"
                  link
                  type="primary"
                  @click="handleProduce(scope.row)"
                >
                  生产
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="所需用量" align="center" prop="count" width="80" />
            <el-table-column label="单位" align="center" prop="unitName" width="80" />
            <el-table-column label="领料数" align="center" prop="pullCount" width="80" />
            <el-table-column label="已退数" align="center" prop="backCount" width="80" />
            <el-table-column label="已用数" align="center" prop="useCount" width="80" />
            <el-table-column label="报废数" align="center" prop="scrapCount" width="80" />
            <el-table-column label="单价" align="center" prop="price" width="80" />
            <el-table-column label="费用" align="center" prop="allPrice" width="80" />
            <el-table-column label="备注" align="center" prop="remark" width="80" />
            <el-table-column label="操作" align="center" min-width="160px" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="openMaterialOut(scope.row)" :disabled="formType != 'process'">
                  领料
                </el-button>
                <el-button link type="primary" @click="openMaterialReturn(scope.row)" :disabled="formType != 'process'">
                  退料
                </el-button>
                <el-button link type="primary" @click="openMaterialUse(scope.row)" :disabled="formType != 'process'">
                  用料
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="2.工序流程" name="process">
          <el-table :data="formData.processItems" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="执行顺序" align="center" prop="sort" />
            <el-table-column label="工序名称" align="center" prop="name" />
            <el-table-column label="负责人员" align="center" prop="userName" />
            <el-table-column label="计价方式" align="center" prop="type" />
            <el-table-column label="工价" align="center" prop="price" />
            <el-table-column label="标准耗时(小时)" align="center" prop="elapsedTime" />
            <el-table-column label="费用" align="center" prop="allPrice" />
            <el-table-column
              label="计划完工日期"
              align="center"
              prop="planFinishTime"
              :formatter="dateFormatter2"
              width="180px"
            />
            <el-table-column label="产品备注" align="center" prop="remark" />
            <!--            <el-table-column-->
            <!--                label="创建时间"-->
            <!--                align="center"-->
            <!--                prop="createTime"-->
            <!--                :formatter="dateFormatter"-->
            <!--                width="180px"-->
            <!--            />-->
            <el-table-column label="操作" align="center" min-width="100px">
              <template #default="scope">
                <div v-if="scope.row.status === 20">
                  <el-button link @click="openProcessAddItem(scope.row)"> 汇报 </el-button>
                  <el-button link @click="handleProcessStatus(scope.row)"> 结束 </el-button>
                  <el-button link type="info" @click="openProcessDetailsItem(scope.row)">
                    详情
                  </el-button>
                </div>

                <div v-else-if="scope.row.status === 30">
                  <el-button link @click="handleProcessStatus(scope.row)"> 返工 </el-button>
                  <el-button link type="info" @click="openProcessDetailsItem(scope.row)">
                    详情
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- <el-tab-pane label="2.验收记录" name="check">
          <el-table :data="formData.checkItems" class="-mt-10px">
            <el-table-column label="验收人员" align="center" prop="userId" />
            <el-table-column
              label="验收时间"
              align="center"
              prop="checkTime"
              :formatter="dateFormatter2"
              width="180px"
            />
            <el-table-column label="合格数量" align="center" prop="passCount" />
            <el-table-column label="不合格数" align="center" prop="failCount" />
            <el-table-column label="报废数量" align="center" prop="scrapCount" />
            <el-table-column label="操作" align="center" min-width="120px" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="openCheck('update', scope.row.id)">
                  编辑
                </el-button>
                <el-button link type="danger" @click="handleCheckDelete(scope.row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane> -->
      </el-tabs>
    </ContentWrap>
  </Dialog>
  <ProducePlanMaterialOut ref="producePlanMaterialOutRef" @success="getList" />
  <ProducePlanMaterialReturn ref="producePlanMaterialReturnRef" @success="getList" />
  <ProducePlanMaterialUse ref="producePlanMaterialUseRef" @success="getList" />
  <ProducePlanCheck ref="producePlanCheckRef" @success="getList" />
  <ProducePlanIn ref="producePlanInRef" @success="getList" />
  <ProducePlanLog ref="producePlanLogRef" @success="getList" />
  <ProducePlanProcessItemsForm ref="producePlanProcessItemsFormRef" @success="getList" />
  <ProducePlanProcessItemsIndex ref="ProducePlanProcessItemsIndexRef" @success="getList" />
  <!-- 采购订单表单 -->
  <PurchaseOrderForm ref="purchaseOrderFormRef" @success="getList" />
  <!-- 生产计划表单 -->
  <ProducePlanForm ref="producePlanFormRef" @success="getList" />
</template>
<script setup lang="ts">
import { ProducePlanApi } from '@/api/erp/produce/plan'
import { ProduceMaterialApi } from '@/api/erp/produce/material'
import { dateFormatter, dateFormatter2, formatDate } from '@/utils/formatTime'
import ProducePlanMaterialOut from './components/ProducePlanMaterialOut.vue'
import ProducePlanMaterialReturn from './components/ProducePlanMaterialReturn.vue'
import ProducePlanMaterialUse from './components/ProducePlanMaterialUse.vue'
import ProducePlanCheck from './components/ProducePlanCheck.vue'
import ProducePlanIn from './components/ProducePlanIn.vue'
import ProducePlanLog from './components/ProducePlanLog.vue'
import ProducePlanProcessItemsForm from './components/ProducePlanProcessItemsForm.vue'
import ProducePlanProcessItemsIndex from './components/ProducePlanProcessItemsIndex.vue'
import PurchaseOrderForm from '@/views/erp/purchase/order/PurchaseOrderForm.vue'
import ProducePlanForm from './ProducePlanForm.vue'

import { ProduceCheckApi } from '@/api/erp/produce/check'
import { DICT_TYPE } from '@/utils/dict'
import { ProduceProcessApi } from '@/api/erp/produce/process'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

defineOptions({ name: 'ProducePlanDetails' })
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  no: undefined,
  productId: undefined,
  productName: undefined,
  productBarCode: undefined,
  productUnitId: undefined,
  orderCount: undefined,
  produceCount: undefined,
  salesOrderId: undefined,
  salesOrderNo: undefined,
  fileUrl: undefined,
  finishPlanTime: undefined,
  realFinishTime: undefined,
  remark: undefined,
  materialItems: [],
  checkItems: [],
  processItems: []
})

const subTabsName = ref('material')
const planId = ref()
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type == 'process' ? '加工' : '详情'
  formType.value = type
  planId.value = id
  await getList()
}

// 封装数据获取方法
const getList = async () => {
  let id = planId.value
  if (!id) return // 处理id不存在的情况
  formData.value = await ProducePlanApi.getProducePlan(id)
  let materialData = await ProduceMaterialApi.getProduceMaterialPage({ planId: formData.value.id })
  formData.value.materialItems = materialData.list

  let processData = await ProduceProcessApi.getProduceProcessPage({ planId: formData.value.id })
  formData.value.processItems = processData.list

  let checkData = await ProduceCheckApi.getProduceCheckPage({ planId: formData.value.id })
  formData.value.checkItems = checkData.list
}

const producePlanMaterialOutRef = ref()
const openMaterialOut = (row: any) => {
  producePlanMaterialOutRef.value.open(row)
}

const producePlanMaterialReturnRef = ref()
const openMaterialReturn = (row: any) => {
  producePlanMaterialReturnRef.value.open(row)
}

const producePlanMaterialUseRef = ref()
const openMaterialUse = (row: any) => {
  producePlanMaterialUseRef.value.open(row)
}

const producePlanCheckRef = ref()
const openCheck = (type: string, id?: number) => {
  producePlanCheckRef.value.open(formData.value.id, type, id)
}

const producePlanLogRef = ref()
const openPlanLog = (type: string) => {
  producePlanLogRef.value.open(formData.value.id, type)
}

const producePlanInRef = ref()
const openIn = () => {
  producePlanInRef.value.open(formData.value)
}

const producePlanProcessItemsFormRef = ref()
// 汇报工序
const openProcessAddItem = (row: any) => {
  producePlanProcessItemsFormRef.value.open(row, 'create')
}

// 结束工序
const handleProcessStatus = async (row: any) => {
  try {
    // TODO: 实现结束工序功能
    if (row.status == '20') {
      await message.confirm('是否确认结束该工序?', '结束工序')
      let data = {
        id: row.id,
        status: '30' // 标记为已完成
      }
      await ProduceProcessApi.updateProduceProcess(data)
      message.success('操作成功')
    } else if (row.status == '30') {
      await message.confirm('是否确认结束该工序并标记为已完成?', '结束工序')
      let data = {
        id: row.id,
        status: '20' // 标记为进行中
      }
      await ProduceProcessApi.updateProduceProcess(data)
    }
    // 刷新列表
    await getList()
  } catch {}
}

// 查看工序详情
const ProducePlanProcessItemsIndexRef = ref()
const openProcessDetailsItem = (row: any) => {
  ProducePlanProcessItemsIndexRef.value.open(row)
}

const finishPlan = async () => {
  try {
    // 删除的二次确认
    await message.confirm(
      '是否确认完成生产计划编号为"' + formData.value.no + '"的数据项?',
      '确认完工'
    )
    // 发起删除
    await ProducePlanApi.finishPlan(formData.value.id)
    message.success('操作成功')
    // 刷新列表
    emit('success')
    dialogVisible.value = false
  } catch {}
}
const handleCheckDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProduceCheckApi.deleteProduceCheck(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
  } catch {}
}

// 采购补货操作 - 直接打开采购订单表单
const purchaseOrderFormRef = ref()
const handlePurchase = async (row: any) => {
  try {
    // 计算需要采购的数量：如果库存不足则采购缺货数量，否则采购所需用料
    const shortageCount = row.count - row.stockCount
    const purchaseCount = shortageCount > 0 ? shortageCount : row.count

    // 构建采购订单项数据
    const purchaseItems = [{
      productId: row.productId,
      productName: row.productName,
      productBarCode: row.productBarCode,
      productUnitName: row.unitName,
      count: purchaseCount,
      productPrice: row.price || 0,
      stockCount: row.stockCount,
      sourcePlanNo: formData.value.no  // 关联的生产计划单号
    }]

    // 直接打开采购订单表单，传入采购物料数据
    purchaseOrderFormRef.value.open('create', undefined, purchaseItems)
  } catch (error) {
    console.error('打开采购表单失败:', error)
    message.error('操作失败')
  }
}

// 生产补货操作 - 直接打开生产计划表单
const producePlanFormRef = ref()
const handleProduce = async (row: any) => {
  try {
    // 计算需要生产的数量：如果库存不足则生产缺货数量，否则生产所需用料
    const shortageCount = row.count - row.stockCount
    const produceCount = shortageCount > 0 ? shortageCount : row.count

    // 构建生产计划预设数据
    const presetData = {
      productId: row.productId,
      productName: row.productName,
      productBarCode: row.productBarCode,
      productUnitId: row.unitId,
      productUnitName: row.unitName,
      produceCount: produceCount,
      orderCount: produceCount,
      stockCount: row.stockCount,
      sourcePlanNo: formData.value.no  // 关联的生产计划单号
    }

    // 直接打开生产计划表单，传入产品数据
    producePlanFormRef.value.open('create', undefined, presetData)
  } catch (error) {
    console.error('打开生产计划表单失败:', error)
    message.error('操作失败')
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const emit = defineEmits(['success'])
</script>
